<template>
  <view class="design-page">
    <!-- 功能按钮区 -->
    <view class="func-bar">
      <div class="func-btn switch-style" @click="openSwitchGoods()">
        <template v-for="item in categoryGoods">
          <image class="switch-style-icon" :src="item.pic"></image>
        </template>
        切换款式
      </div>
      <div class="flex save-preview">
        <div class="func-btn preview" @click="previewTap()">预览</div>
        <div class="func-btn preview save">保存</div>
      </div>
    </view>

    <div class="relative canvas-content">
      <!-- 颜色选择器 -->
      <view class="flex color-controller">
        <label v-for="color in useDesignerGood.activeGood?.bodyPosition" :key="color.skuColorRgb" class="relative color-item" @click="onTapColor(color)">
          <view
            class="color-item-view"
            :class="{
              active: useDesignerGood.activePosition?.id == color.id,
            }"
            :style="{ backgroundColor: color.skuColorRgb }"
          ></view>
        </label>
      </view>

      <!-- T恤展示区 -->
      <view id="app-modal-canvas" class="relative">
        <canvas
          id="controllCanvas"
          ref="controlCanvasRef"
          class="controll-canvas"
          type="2d"
          :style="{
            width: modalCanvas.width + 'px',
            height: modalCanvas.height + 'px',
          }"
          :width="modalCanvas.width"
          :height="modalCanvas.height"
          @touchmove="touchMove"
          @touchstart="touchStart"
          @touchend="touchUp"
          @mousedown="touchStart"
          @mousemove="touchMove"
          @mouseup="touchUp"
          @click="canvasClickTap"
        />
      </view>

      <!-- 右侧工具栏 -->
      <view class="right-tools">
        <div class="items-center">
          <view class="item-center" @click="clearDesign">
            <img class="img" mode="widthFix" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%201931%402x.png" />
          </view>
          <text class="txt">清空</text>
        </div>

        <div class="items-center">
          <view class="item-center" @click="bindBgColor">
            <img class="img" mode="widthFix" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%201899%402x.png" />
          </view>
          <text class="txt">底色</text>
        </div>

        <div class="items-center" @click="tapZIndex">
          <view class="item-center">
            <img class="img" mode="widthFix" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%201901%402x.png" />
          </view>
          <text class="txt">图层</text>
        </div>

        <div class="items-center">
          <view class="item-center" @click="tapChangePosition()">
            <img class="img" mode="widthFix" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%201906%402x.png" />
          </view>
          <text class="txt">{{ towardShapePosition.name }}</text>
        </div>
      </view>

      <DraggableList v-if="draggableListShow" ref="draggableListRef" @update="updateAllNodeZIndex"></DraggableList>
    </div>

    <!-- 底部款式与定制区 -->
    <view class="bottom-model">
      <!-- 款式Tab -->
      <view class="items-center" :class="{ show: !isTextImgNode }">
        <div class="item-center">
          <img class="img-item" mode="widthFix" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%201920%402x.png" />
          <div class="txt-item">AI设计</div>
        </div>
        <div class="item-center" @click="materialCateTap()">
          <img class="img-item" mode="widthFix" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%201915%402x.png" />
          <div class="txt-item">素材库</div>
        </div>
        <div class="item-center" @click="textTap()">
          <img class="img-item" mode="widthFix" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%201910%402x.png" />
          <div class="txt-item">文字</div>
        </div>
        <div class="item-center" @click="imgTap(null)">
          <img class="img-item" mode="widthFix" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%201908%402x.png" />
          <div class="txt-item">照片</div>
        </div>
      </view>

      <!--  微调 控制按钮  -->
      <view class="items-center" :class="{ show: isTextImgNode }">
        <BottomTools ref="bottomToolsRef" style="width: 100%; display: flex; justify-content: space-around" @close="updateSelectNode(null)" @bind-tool="bindBottomTool"></BottomTools>
      </view>
      <!--  微调 控制按钮  -->
      <view class="items-center" :class="{ show: isTextImgNode }">
        <BottomTools ref="bottomToolsRef" style="width: 100%; display: flex; justify-content: space-around" @close="updateSelectNode(null)" @bind-tool="bindBottomTool"></BottomTools>
      </view>

      <ZIndexTools ref="zIndexToolsRef" @bind-tool="bindZIndexTool"></ZIndexTools>
      <MoveTools ref="moveToolsRef" @bind-tool="bindMoveTool"></MoveTools>
      <FlipTools ref="flipToolsRef" @bind-tool="bindFlipTool"></FlipTools>
    </view>

    <SwitchGoods ref="switchGoodsRef"></SwitchGoods>

    <AddText ref="addTextRef" @change="updateText"></AddText>
    <ShapeImage ref="shapeImageRef" @select-cate="selectCateTap"></ShapeImage>
    <ColorPicker ref="colorPickerRef" @color-change="updateBgColorPicker"></ColorPicker>

    <PreviewShape ref="previewShapeRef"></PreviewShape>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive, nextTick, watch, unref, shallowRef, toRaw, provide } from 'vue';
import { CanvasCut } from '@/canvasCut/CanvasCut';
import { chooseImg, downImg, selectQuery } from '@/canvasCut/utils/ImgUtil';
import { AiShirtCanvas } from '@/canvasCut/core/AiShirtCanvas';
import { ImageNode } from '@/canvasCut/package/node/imageNode';
import { useCanvasDiv } from '@/pages/design/hooks/useCanvasDiv';
import SwitchGoods from '@/pages/design/components/SwitchGoods.vue';
import { useDesignerGoodState } from '@/state/modules/DesignerGoodState';
import { useEvent } from '@/pages/design/hooks/useEvent';
import AddText from '@/pages/design/components/AddText.vue';
import ShapeImage from '@/pages/design/components/ShapeImage.vue';
import { TextNode } from '@/canvasCut/package/node';
import BottomTools from '@/pages/design/components/BottomTools.vue';
import ZIndexTools from '@/pages/design/components/ZIndexTools.vue';
import MoveTools from '@/pages/design/components/MoveTools.vue';
import FlipTools from '@/pages/design/components/FlipTools.vue';
import DraggableList from '@/components/DraggableList.vue';
import ColorPicker from '@/pages/design/components/ColorPicker.vue';
import PreviewShape from '@/pages/design/components/PreviewShape.vue';

const switchGoodsRef = shallowRef(null);
const addTextRef = shallowRef(null);

const openSwitchGoods = () => {
  switchGoodsRef.value.open();
};

const previewShapeRef = shallowRef(null);
const previewTap = () => {
  updateSelectNode(null);
  previewShapeRef.value.open(aiShirtCanvas);
};

const modalCanvas = reactive({
  width: 0,
  height: 0,
  show: false,
  controll: {
    show: false,
    x: 0,
    y: 0,
    width: 0,
    height: 0,
  },
});
let canvasCut;
let aiShirtCanvas: AiShirtCanvas;

const canvasBtnEvent = (canvasBtn) => {
  console.log('canvasBtnEvent', canvasBtn);
  const btnType = canvasBtn.btnType;
  const nodeType = canvasBtn.selectNodeBox._node._type;

  if (btnType === 'replace' && nodeType === 'image') {
    console.log('图片 替换按钮');
    imgTap(canvasBtn.selectNodeBox._node.__id__);
  } else if (btnType === 'edit' && nodeType === 'text') {
    console.log('文字 编辑按钮按钮');
    addTextRef.value.open(canvasBtn.selectNodeBox._node);
  } else if (btnType === 'del') {
    console.log('删除');
    aiShirtCanvas.delNode(selectNode.value.__id__);
  }
};

const zIndexToolsRef = shallowRef(null);
const moveToolsRef = shallowRef(null);
const flipToolsRef = shallowRef(null);
const bindBottomTool = (bottomTool) => {
  if (bottomTool.key === 'replace') {
    imgTap(selectNode.value.__id__);
  } else if (bottomTool.key === 'reset') {
    console.log('复位');
    selectNode.value.resetLocation();
    aiShirtCanvas.draw();
  } else if (bottomTool.key === 'zIndex') {
    console.log('层级');
    zIndexToolsRef.value.open(true);
  } else if (bottomTool.key === 'location') {
    console.log('微调');
    moveToolsRef.value.open(true);
  } else if (bottomTool.key === 'flip') {
    console.log('翻转');
    flipToolsRef.value.open(true);
    updateSelectNode(null);
  }
};

const bindZIndexTool = (zIndexToolType) => {
  console.log('zIndexTool', zIndexToolType);
  aiShirtCanvas.changeNodeZIndex(selectNode.value, zIndexToolType);
  aiShirtCanvas.draw();
};

const bindMoveTool = (moveToolType) => {
  console.log('moveTool', moveToolType);
  selectNode.value.moveXY(moveToolType);
  aiShirtCanvas.draw();
};

const bindFlipTool = (flipToolType) => {
  console.log('flipToolType', flipToolType);
  selectNode.value.changeFlip(flipToolType);
  aiShirtCanvas.draw();
};

const updateAllNodeZIndex = (newNodeList) => {
  aiShirtCanvas.nodeSort(newNodeList);
  console.log('updateAllNodeZIndex', toRaw(newNodeList));
  aiShirtCanvas.draw();
};

// 拖动事件
const { touchStart, touchMove, touchUp, selectNode, updateSelectNode, initAIShirtCanvas } = useEvent({ canvasBtnEvent });
let aiCanvas;

const draggableListShow = ref(false);

const isTextImgNode = computed(() => {
  // return  true
  const activeSelectNode = unref(selectNode);
  if (activeSelectNode) {
    return activeSelectNode._type === 'text' || activeSelectNode._type === 'image';
  }
  zIndexToolsRef.value?.open(false);
  moveToolsRef.value?.open(false);
  flipToolsRef.value?.open(false);
  draggableListShow.value = false;
  return false;
});

const { getCanvasQuery } = useCanvasDiv(selectNode);

// 初始化商品数据
const useDesignerGood = useDesignerGoodState();
useDesignerGood.init();

onMounted(async () => {
  const res = await selectQuery('#app-modal-canvas');
  modalCanvas.width = res.width;
  modalCanvas.height = res.height;
  modalCanvas.show = true;
});

const modelCanvasCtx = shallowRef(null);
provide('modelCanvasCtx', modelCanvasCtx);

// 当前渲染的方向
let towardShapePosition = computed(() => {
  return useDesignerGood.towardPosition;
});
const controlCanvasRef = shallowRef(null);
watch(
  [() => controlCanvasRef.value, () => towardShapePosition.value],
  async () => {
    console.error('controlCanvasRef.value', controlCanvasRef.value);
    if (controlCanvasRef.value || true) {
      setTimeout(async () => {
        const { ctx, canvas } = await getCanvasQuery('#controllCanvas');
        modelCanvasCtx.value = ctx;

        if (towardShapePosition.value.AICanvas) {
          // 存在AICanvas
          console.log('存在AICanvas', towardShapePosition.value);
          aiShirtCanvas = towardShapePosition.value.AICanvas;
          aiShirtCanvas.draw();
          return;
        }
        // 当前 选中的款式及颜色
        const towardPosition = towardShapePosition.value;
        const CanvasCutOption = {
          width: modalCanvas.width,
          height: modalCanvas.height,
        };
        // 初始化对象
        canvasCut = new CanvasCut(CanvasCutOption, ctx, canvas);
        //
        // 渲染默认衣服
        await canvasCut.drawModalImg(towardPosition.img);

        // 渲染可操作区域
        modalCanvas.controll = canvasCut.getControllerConfig(toRaw(towardPosition));
        console.error('CanvasCutOption', CanvasCutOption);
        const { x, y, width, height } = modalCanvas.controll;

        console.log({ x, y, width, height });
        aiShirtCanvas = new AiShirtCanvas(canvas, ctx, {
          x,
          y,
          width,
          height,
          backgroundPosition: toRaw(towardPosition),
          canvasCut,
          canvasWidth: modalCanvas.width,
          canvasHeight: modalCanvas.height,
        });
        towardShapePosition.value.AICanvas = aiShirtCanvas;
        // 给事件 注入 aiShirtCanvas
        initAIShirtCanvas(aiShirtCanvas);
        aiShirtCanvas.showController(modalCanvas.controll);
        // console.log('aiShirtCanvas', aiShirtCanvas);
      }, 1000);
    }
  },
  { flush: 'post', immediate: true },
);

/**
 * 图片选择
 */
const imgTap = (nodeId) => {
  chooseImg().then(async (res) => {
    // 最大宽度/ 高度
    const { image, imageData, x, y, w, h, scale } = await aiShirtCanvas.getImage(res);
    console.log('image', image, x, y, w, h, scale);
    const targetNode = aiShirtCanvas.getTargetNodeById(nodeId);
    console.log('图片选择 targetNode', targetNode);
    const centerXY = [modalCanvas.controll.x + modalCanvas.controll.width / 2, modalCanvas.controll.y + modalCanvas.controll.height / 2];

    if (!targetNode) {
      const imageNode = new ImageNode({
        imageData: image,
        x: centerXY[0] - w / 2,
        y: centerXY[1] - h / 2,
        width: w,
        height: h,
        type: 'image',
        isSelected: true,
        scale: scale,
        canvas: aiShirtCanvas.getCanvas(),
        centerXY: centerXY,
        _sourceImageData: imageData,
        canvasHeight: modalCanvas.height,
        canvasWidth: modalCanvas.width,
      });
      aiShirtCanvas.addNode(imageNode);
      // 更新选择的图片
      updateSelectNode(imageNode);
    } else {
      const targetNodeCenterXY = [targetNode.x + targetNode.width / 2, targetNode.y + targetNode.height / 2];

      targetNode.updateSrc({
        imageData: image,
        x: targetNodeCenterXY[0] - w / 2,
        y: targetNodeCenterXY[1] - h / 2,
        width: w,
        height: h,
        type: 'image',
        isSelected: true,
        _sourceImageData: imageData,
        canvas: aiShirtCanvas.getCanvas(),
      });
    }
    aiShirtCanvas.draw();
  });
};

const textTap = () => {
  addTextRef.value.open();
};

const shapeImageRef = shallowRef(null);
const materialCateTap = () => {
  shapeImageRef.value.open();
};

const updateText = (textOption) => {
  const { width, height } = textOption.textStyle;
  const centerXY = [modalCanvas.controll.x + modalCanvas.controll.width / 2, modalCanvas.controll.y + modalCanvas.controll.height / 2];
  console.log('updateText', { centerXY, width, height });

  const newTextOption = {
    ...toRaw(textOption),
    width: width,
    height: height,
    canvas: aiShirtCanvas.getCanvas(),
    canvasHeight: modalCanvas.height,
    canvasWidth: modalCanvas.width,
  };
  console.error('textOption', textOption);
  if (!textOption.__id__ && !textOption.textStr) return;
  // 修改旧的节点
  if (textOption.__id__) {
    const targetNode = aiShirtCanvas.getTargetNodeById(textOption.__id__);

    const targetNodeCenterXY = [targetNode.x + targetNode.width / 2, targetNode.y + targetNode.height / 2];
    newTextOption.x = targetNodeCenterXY[0] - width / 2;
    newTextOption.y = targetNodeCenterXY[1] - height / 2;

    if (targetNode._type === 'text') {
      targetNode.updateTxt(newTextOption);
      updateSelectNode(targetNode);
      aiShirtCanvas.draw();
      return;
    }
  }
  // 添加新节点
  newTextOption.x = centerXY[0] - width / 2;
  newTextOption.y = centerXY[1] - height / 2;

  const textNode = new TextNode(newTextOption);
  aiShirtCanvas.addNode(textNode);
  addTextRef.value.setId(textNode.__id__);
  updateSelectNode(textNode);
  aiShirtCanvas.draw();
};

const selectCateTap = (shapeCate) => {
  downImg(shapeCate.pic).then(async (res) => {
    // 最大宽度/ 高度
    const { image, imageData, x, y, w, h, scale } = await aiShirtCanvas.getImage(res);
    console.log('image', image, x, y, w, h, scale);
    const centerXY = [modalCanvas.controll.x + modalCanvas.controll.width / 2, modalCanvas.controll.y + modalCanvas.controll.height / 2];

    const imageNode = new ImageNode({
      imageData: image,
      x: centerXY[0] - w / 2,
      y: centerXY[1] - h / 2,
      width: w,
      height: h,
      type: 'image',
      isSelected: true,
      scale: scale,
      canvas: aiShirtCanvas.getCanvas(),
      centerXY: centerXY,
      _sourceImageData: imageData,
      canvasHeight: modalCanvas.height,
      canvasWidth: modalCanvas.width,
    });
    aiShirtCanvas.addNode(imageNode);
    // 更新选择的图片
    updateSelectNode(imageNode);
  });
};

/** 切换 款式的颜色 */
const onTapColor = (color) => {
  console.log('ssssssssssssssssssssss', useDesignerGood, color);
  useDesignerGood.setActivePosition(color);
};

// 方法：清空设计
const clearDesign = () => {
  aiShirtCanvas.clear();
  updateSelectNode(null);
};

const colorPickerRef = shallowRef(null);
const bindBgColor = () => {
  colorPickerRef.value.open(aiShirtCanvas.bgColor);
};
const updateBgColorPicker = (color) => {
  aiShirtCanvas.bgColor = color;
  aiShirtCanvas.draw();
};

const draggableListRef = shallowRef(null);
const tapZIndex = () => {
  draggableListShow.value = true;
  setTimeout(() => {
    draggableListRef.value.open(aiShirtCanvas.allNodeObject);
  }, 100);
};

const tapChangePosition = () => {
  useDesignerGood.changeColorBodyPosition();
};
</script>

<style lang="scss">
canvas {
  position: relative;
  z-index: 0;
}

page {
  background: #f3f7f8;
  height: 100vh;
  padding: 16rpx 0 32rpx;
  box-sizing: border-box;
}

canvas {
  transform: translateZ(0);
  will-change: transform;
}

.design-page {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 48rpx);
  background: #ffffff;
  box-shadow: 0rpx 2rpx 8rpx 2rpx rgba(0, 0, 0, 0.08);
  border-radius: 16rpx 16rpx 16rpx 16rpx;
}

.nav-title {
  font-size: 34rpx;
  font-weight: 500;
}

.func-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;

  .switch-style {
    display: flex;
    align-items: center;
    justify-content: center;
    //width: 206rpx;
    height: 54rpx;
    background: #f3f7f8;
    border-radius: 28rpx 28rpx 28rpx 28rpx;
    font-weight: 400;
    font-size: 28rpx;
    color: #222222;
    padding: 0 24rpx;

    .switch-style-icon {
      width: 36rpx;
      height: 32rpx;
      margin-right: 10rpx;
    }
  }

  .preview {
    width: 132rpx;
    height: 54rpx;
    line-height: 54rpx;
    background: #f3f7f8;
    border-radius: 28rpx 28rpx 28rpx 28rpx;
    font-weight: 400;
    font-size: 28rpx;
    color: #222222;
    text-align: center;
  }

  .save {
    background-color: #f25a27;
    color: #fff;
  }
}

.canvas-content {
  display: flex;
  height: 0;
  flex: 1;
  margin: 30rpx 50rpx 0;
  background: #f3f7f8;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
}
</style>

<style lang="scss" scoped>
.flex {
  display: flex;
}

.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

.save-preview {
  gap: 16rpx;
}

.canvas-content {
  position: relative;
  margin: 0 16rpx;

  .color-controller {
    position: absolute;
    height: 36rpx;
    gap: 16rpx;
    left: 20rpx;
    top: 20rpx;
    z-index: 10;

    .color-item {
      .color-item-view {
        width: 36rpx;
        height: 36rpx;
        border-radius: 50%;
        opacity: 0.5;
        border: 4rpx solid rgba(242, 90, 39, 0);

        &.active {
          opacity: 1;
          border: 4rpx solid #222;
        }
      }
    }
  }
}

#app-modal-canvas {
  position: relative;
  //top: -100rpx;
  width: 100%;
  z-index: 1;
  background: rgba(111, 111, 111, 0.29);

  .modal-canvas {
    width: 100%;
    height: 100%;
    z-index: 1;
  }

  .controll-canvas {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
  }
}

.right-tools {
  position: absolute;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  right: 24rpx;
  bottom: 36rpx;
  z-index: 10;
  height: max-content;

  .items-center {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16rpx;

    .item-center {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 84rpx;
      height: 84rpx;
      border-radius: 50%;
      background: #ffffff;

      .img {
        width: 48rpx;
      }
    }

    .txt {
      font-size: 24rpx;
      color: #222222;
    }
  }
}

.bottom-model {
  position: relative;
  height: 162rpx;
  overflow: hidden;

  .items-center {
    width: 100%;
    position: absolute;
    height: 162rpx;
    display: flex;
    justify-content: space-between;
    padding: 50rpx 94rpx;
    transition: all 0.3s ease-in-out;
    transform: translateY(100%);
    opacity: 0;
    &.show {
      transform: translateY(0);
      opacity: 1;
    }
    .left-btn {
      position: absolute;
      left: 16rpx;
      .left-btn-icon {
        width: 48rpx;
        height: 60rpx;
      }
    }

    .item-center {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      gap: 8rpx;
      font-size: 22rpx;
      color: #222222;
    }

    .img-item {
      width: 32rpx;
    }

    .txt-item {
      margin: 0 8rpx;
      height: 28rpx;
      line-height: 28rpx;
      font-size: 22rpx;
      color: #222222;
    }
  }
}
</style>
